﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using Microsoft.WindowsMobile.DirectX;
using System.IO;
using System.Diagnostics;

namespace PFD
{
    public class RenderTextureX : IRenderTexture
    {
        /// <summary>
        /// Store a DirectX texture object
        /// </summary>
        Microsoft.WindowsMobile.DirectX.Direct3D.Texture tName;

        /// <summary>
        /// Maintain a flag to indicate whether or not this object has already been disposed
        /// </summary>
        bool Disposed = false;

        /// <summary>
        /// The original texture file name
        /// </summary>
        string TextureFileName;

        public Texture Texture { get { return tName; } }

        #region IRenderTexture Members

        /// <summary>
        /// Provide a property to access the name of the texture. This is not supported for Direct3D
        /// </summary>
        public uint Name
        {
            get { throw new NotSupportedException(); }
        }

        #endregion

        /// <summary>
        /// Constructor. Creates a new Texture object from provided stream for provided device.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="d"></param>
        public RenderTextureX(string s, Device d)
        {
            TextureFileName = s;
            OnDeviceLost(d);
        }

        /// <summary>
        /// To be called after the device got lost
        /// </summary>
        /// <param name="d"></param>
        public void OnDeviceLost(Device d)
        {
            if (tName != null)
            {
                tName.Dispose();
                while (!tName.Disposed) ;
                tName = null;
            }
            int free = d.GetAvailablePoolMem(Pool.VideoMemory);
            Debug.WriteLine("Free video memory before texture load = " + free.ToString());
            tName = Microsoft.WindowsMobile.DirectX.Direct3D.TextureLoader.FromFile(d, TextureFileName);
            free = d.GetAvailablePoolMem(Pool.VideoMemory);
            Debug.WriteLine("Free video memory after texture load = " + free.ToString());
        }


        #region IDisposable Members

        /// <summary>
        /// Dispose this object and all related objects.
        /// </summary>
        public void Dispose()
        {
            if (!Disposed)
            {
                tName.Dispose();
                Disposed = true;
            }
        }

        #endregion
    }
}
